package com.hanbang.gycatering.classify;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.hanbang.gangyu.R;
import com.hanbang.gycatering.adpater.BannerAdAdapter;
import com.hanbang.gycatering.application.ActivityManager;
import com.hanbang.gycatering.application.MyApplication;
import com.hanbang.gycatering.bean.BannerAdData;
import com.hanbang.gycatering.bean.ProductDetailData;
import com.hanbang.gycatering.homepage.BaseActivity;
import com.hanbang.gycatering.myviews.CircleImageView;
import com.hanbang.gycatering.myviews.ColoredRatingBar;
import com.hanbang.gycatering.shoppingcart.ShoppingCart;
import com.hanbang.gycatering.utils.HttpInterfaces;
import com.hanbang.gycatering.utils.JsonHelper;
import com.hanbang.gycatering.utils.MyLog;
import com.hanbang.gycatering.utils.MyRequestCallBack;
import com.hanbang.gycatering.utils.MySharedPreferences;
import com.hanbang.gycatering.utils.MyToast;
import com.hanbang.gycatering.utils.SystemTools;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

public class ProductDetail extends BaseActivity {
	private String TAG = ProductDetail.class.getSimpleName();
	private BannerAdAdapter bannerAdAdapter = null;
	private ArrayList<BannerAdData> bannerAdDatas = new ArrayList<BannerAdData>();
	private PullToRefreshScrollView scrollView = null;
	private int id = -1;
	private FrameLayout animationViewGroup = null;
	private TextView addGouwuChe = null;
	private LinearLayout guanzhu = null;
	private TextView gouwucheNum = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		id = getIntent().getIntExtra("id", id);
		setContentView(R.layout.productdetail);
		initView();
		setTheClick();
		getProductDetails();
		checkFollow();
		checkGouWuCheNumber();
	}

	private void initView() {
		((TextView) findViewById(R.id.top_bar_title)).setText("产品详情");
		scrollView = (PullToRefreshScrollView) findViewById(R.id.scrollview);
		scrollView.setMode(Mode.PULL_FROM_START);
		scrollView.setOnRefreshListener(new OnRefreshListener<ScrollView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
				getProductDetails();
			}
		});
		// 初始化广告条 数据完成的时候要调用start
		bannerAdAdapter = new BannerAdAdapter(this,
				(RelativeLayout) findViewById(R.id.banner_ad), bannerAdDatas);
		bannerAdAdapter.setWidthAndHeight(1, 1);

		findViewById(R.id.comment).setOnClickListener(myOncClickListener);
		addGouwuChe = (TextView) findViewById(R.id.jiaru);
		guanzhu = (LinearLayout) findViewById(R.id.guanzhu);
		gouwucheNum = (TextView) findViewById(R.id.gwc_number);

	}

	private OnClickListener myOncClickListener = new OnClickListener() {
		@Override
		public void onClick(View view) {
			Intent intent = new Intent();
			switch (view.getId()) {
			case R.id.comment:
				intent.setClass(ProductDetail.this, CommentActivity.class);
				intent.putExtra("id", id);
				startActivity(intent);
				break;
			case R.id.gouwuche:
				intent.setClass(ProductDetail.this, ShoppingCart.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
				startActivity(intent);
				// 销毁分类的之类界面
				ActivityManager.getInstance().popActivity(ClassifyList.class);
				break;
			case R.id.guanzhu:
				addfollow();
				break;
			case R.id.jiaru:
				addGouWuChe();
				break;
			default:
				break;
			}
		}
	};

	private void setTheClick() {
		super.setBackArrows((ImageView) findViewById(R.id.top_bar_left_image));
		guanzhu.setOnClickListener(myOncClickListener);
		addGouwuChe.setOnClickListener(myOncClickListener);
		findViewById(R.id.gouwuche).setOnClickListener(myOncClickListener);
	}

	private void addGouWuChe() {

		if (isLogin(true)) {
			MyLog.e(TAG,
					userData.getUserpassword() + "   "
							+ userData.getUserphone());
			addGouwuChe.setEnabled(false);
			((MyApplication) getApplicationContext()).httpUtils.send(
					HttpMethod.GET, HttpInterfaces.addcar + "&id=" + id
							+ "&password=" + userData.getUserpassword()
							+ "&userphone=" + userData.getUserphone(),
					new MyRequestCallBack<String>(ProductDetail.this,
							getString(R.string.loadding)) {
						@Override
						public void onFailure(HttpException error, String msg) {
							super.onFailure(error, msg);
							addGouwuChe.setEnabled(true);
						}

						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							super.onSuccess(responseInfo);
							try {
								JSONObject json = new JSONObject(
										responseInfo.result);
								int state = json.getInt("state");
								if (state == 1) {
									if (bannerAdAdapter != null) {
										int spNum = MySharedPreferences
												.getSharedPreferencesKeyAndValue(
														ProductDetail.this,
														MySharedPreferences.USER_DATA,
														"gouwucheNumber", 0);
										if (spNum == -1) {
											spNum = 0;
										}
										MySharedPreferences
												.setSharedPreferencesKeyAndValue(
														ProductDetail.this,
														MySharedPreferences.USER_DATA,
														"gouwucheNumber",
														spNum + 1);
										setAnim(bannerAdAdapter
												.getCurrentItemView()
												.getDrawable(),
												scrollView,
												((RelativeLayout) findViewById(R.id.gouwuche))
														.getChildAt(1), 1000,
												new AnimationListener() {

													@Override
													public void onAnimationStart(
															Animation animation) {
														addGouwuChe
																.setEnabled(false);
													}

													@Override
													public void onAnimationEnd(
															Animation animation) {
														if (animationViewGroup != null) {
															animationViewGroup
																	.removeAllViews();
														}
														addGouwuChe
																.setEnabled(true);
														checkGouWuCheNumber();
													}

													@Override
													public void onAnimationRepeat(
															Animation animation) {

													}
												});
									} else {
										addGouwuChe.setEnabled(true);
									}
								} else if (state == -100) {
									addGouwuChe.setEnabled(true);
									passwordIsError(false);
								} else {
									addGouwuChe.setEnabled(true);
								}
								MyToast.show(ProductDetail.this,
										json.getString("erro"),
										Toast.LENGTH_SHORT);

							} catch (JSONException e) {
								e.printStackTrace();
								addGouwuChe.setEnabled(true);
							}
						}
					});
		}

	}

	private void getProductDetails() {
		((MyApplication) getApplicationContext()).httpUtils.send(
				HttpMethod.GET, HttpInterfaces.productdetails + "&id=" + id,
				new MyRequestCallBack<String>(ProductDetail.this,
						getString(R.string.loadding)) {
					@Override
					public void onFailure(HttpException error, String msg) {
						super.onFailure(error, msg);
						scrollView.onRefreshComplete();
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						super.onSuccess(responseInfo);
						try {
							JSONObject json = new JSONObject(
									responseInfo.result);
							int state = json.getInt("state");
							if (state == 1) {
								JSONArray info = json.getJSONArray("info");
								ProductDetailData detailData = JsonHelper
										.parseObject(info.getJSONObject(0)
												.getJSONArray("product")
												.getJSONObject(0),
												ProductDetailData.class);
								upDateUI(detailData);
								// 评论数与评论星数
								JSONObject reviews = info.getJSONObject(1)
										.getJSONArray("reviews")
										.getJSONObject(0);
								// 星数
								((ColoredRatingBar) findViewById(R.id.coloredRatingBar))
										.setRating((float) reviews
												.getDouble("star"));
								// 评论总人数
								((TextView) findViewById(R.id.comment_count))
										.setText("(" + reviews.getInt("count")
												+ ")人评论");
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}
						scrollView.onRefreshComplete();
					}
				});
	}

	private void upDateUI(ProductDetailData data) {
		if (data != null) {
			bannerAdDatas.clear();
			if (data.getImg1() != null && !data.getImg1().equals("")) {
				BannerAdData bannerAdData = new BannerAdData();
				bannerAdData.setPath(data.getImg1());
				bannerAdDatas.add(bannerAdData);
			}
			if (data.getImg2() != null && !data.getImg2().equals("")) {
				BannerAdData bannerAdData = new BannerAdData();
				bannerAdData.setPath(data.getImg2());
				bannerAdDatas.add(bannerAdData);
			}
			if (data.getImg3() != null && !data.getImg3().equals("")) {
				BannerAdData bannerAdData = new BannerAdData();
				bannerAdData.setPath(data.getImg3());
				bannerAdDatas.add(bannerAdData);
			}
			if (data.getImg4() != null && !data.getImg4().equals("")) {
				BannerAdData bannerAdData = new BannerAdData();
				bannerAdData.setPath(data.getImg4());
				bannerAdDatas.add(bannerAdData);
			}
			if (data.getImg5() != null && !data.getImg5().equals("")) {
				BannerAdData bannerAdData = new BannerAdData();
				bannerAdData.setPath(data.getImg5());
				bannerAdDatas.add(bannerAdData);
			}
			bannerAdAdapter.notifyDataSetChanged();
			bannerAdAdapter.start();
			if (data.getName() != null) {
				((TextView) findViewById(R.id.name)).setText(data.getName());
			}
			((TextView) findViewById(R.id.price)).setText("¥ "
					+ SystemTools.roundString(data.getPrice(), 2));

			TextView price2 = (TextView) findViewById(R.id.price2);
			price2.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); // 中划线
			price2.setText("¥"
					+ SystemTools.roundString(data.getMarkprice(), 2));

			if (data.getCode() != null && !data.getCode().equals("")) {
				((TextView) findViewById(R.id.cpbh)).setText(data.getCode());
			} else {
				((TextView) findViewById(R.id.cpbh)).setText("未知");
			}
			((TextView) findViewById(R.id.salecount)).setText(String
					.valueOf(data.getSalecount()));
			if (data.getBrand() != null && !data.getBrand().equals("")) {
				((TextView) findViewById(R.id.brand)).setText(data.getBrand());
			} else {
				((TextView) findViewById(R.id.brand)).setText("未知");
			}
			((TextView) findViewById(R.id.freight)).setText(data.getFreight());
			if (data.getService() != null && !data.getService().equals("")) {
				((TextView) findViewById(R.id.service)).setText(data
						.getService());
			} else {
				((TextView) findViewById(R.id.service)).setText("未知");
			}
			if (data.getHint() != null && !data.getHint().equals("")) {
				((TextView) findViewById(R.id.hint)).setText(data.getHint());
			} else {
				((TextView) findViewById(R.id.hint)).setText("未知");
			}
		}
	}

	/*
	 * 检查购物车数量
	 */
	private void checkGouWuCheNumber() {
		if (isLogin(false)) {
			((MyApplication) getApplicationContext()).httpUtils.send(
					HttpMethod.GET, HttpInterfaces.carsum + "&password="
							+ userData.getUserpassword() + "&userphone="
							+ userData.getUserphone(),
					new MyRequestCallBack<String>(ProductDetail.this, null) {
						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							super.onSuccess(responseInfo);
							try {
								JSONObject json = new JSONObject(
										responseInfo.result);
								int state = json.getInt("state");
								if (state == 1) {
									int info = json.getInt("info");
									if (info > 0) {
										if (info < 100) {
											gouwucheNum.setText(info + "");
											gouwucheNum
													.setVisibility(View.VISIBLE);
										} else {
											gouwucheNum.setText("99+");
										}
									} else {
										gouwucheNum.setVisibility(View.GONE);
									}
									MySharedPreferences
											.setSharedPreferencesKeyAndValue(
													ProductDetail.this,
													MySharedPreferences.USER_DATA,
													"gouwucheNumber", info);
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}

						}
					});
		}
	}

	/*
	 * 检查是否关注
	 */
	private void checkFollow() {
		if (isLogin(false)) {
			((MyApplication) getApplicationContext()).httpUtils.send(
					HttpMethod.GET, HttpInterfaces.checkfollow + "&id=" + id
							+ "&password=" + userData.getUserpassword()
							+ "&userphone=" + userData.getUserphone(),
					new MyRequestCallBack<String>(ProductDetail.this, null) {
						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							super.onSuccess(responseInfo);
							try {
								JSONObject json = new JSONObject(
										responseInfo.result);
								int state = json.getInt("state");
								if (state == 1) {
									// 已经关注
									((ImageView) guanzhu.getChildAt(0))
											.setColorFilter(getResources()
													.getColor(R.color.red));
									((TextView) guanzhu.getChildAt(1))
											.setText("已关注");
								} else if (state == 0) {
									// 未关注
									((ImageView) guanzhu.getChildAt(0))
											.setColorFilter(null);
									((TextView) guanzhu.getChildAt(1))
											.setText("关注");
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}

						}
					});
		}
	}

	/*
	 * guanz
	 */
	private void addfollow() {
		if (isLogin(false)) {
			((MyApplication) getApplicationContext()).httpUtils.send(
					HttpMethod.GET, HttpInterfaces.addfollow + "&id=" + id
							+ "&password=" + userData.getUserpassword()
							+ "&userphone=" + userData.getUserphone(),
					new MyRequestCallBack<String>(ProductDetail.this,
							getString(R.string.loadding)) {
						@Override
						public void onSuccess(ResponseInfo<String> responseInfo) {
							super.onSuccess(responseInfo);
							try {
								JSONObject json = new JSONObject(
										responseInfo.result);
								int state = json.getInt("state");
								if (state == 1) {
									// 关注成功
									((ImageView) guanzhu.getChildAt(0))
											.setColorFilter(getResources()
													.getColor(R.color.red));
									((TextView) guanzhu.getChildAt(1))
											.setText("已关注");
								} else if (state == 2) {
									// 取消关注成功
									((ImageView) guanzhu.getChildAt(0))
											.setColorFilter(null);
									((TextView) guanzhu.getChildAt(1))
											.setText("关注");
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}

						}
					});
		}
	}

	// 加入购物车的动画
	/**
	 * 动画效果设置
	 * 
	 * @param drawable
	 *            将要加入购物车的商品
	 * @param start_location
	 *            起始位置
	 */
	private View setAnim(Drawable drawable, View startView, View endView,
			int duration, AnimationListener animationListener) {
		int[] startLocation = new int[2];
		int[] endtLocation = new int[2];
		startView.getLocationInWindow(startLocation);
		endView.getLocationInWindow(endtLocation);
		if (animationViewGroup == null) {
			animationViewGroup = createAnimLayout();
		}
		Animation mScaleAnimation = new ScaleAnimation(1.5f, 0.4f, 1.5f, 0.4f,
				Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
				0.5f);
		mScaleAnimation.setDuration(duration);
		mScaleAnimation.setFillAfter(true);

		CircleImageView iview = new CircleImageView(this);
		iview.setImageDrawable(drawable);
		BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
		Bitmap b = iview.getRoundedCornerBitmap(bitmapDrawable.getBitmap());
		iview.setImageDrawable(new BitmapDrawable(getResources(), b));

		View view = addViewToAnimLayout(animationViewGroup, iview,
				startLocation);
		iview.measure(View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
				.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
		int endX = endtLocation[0] - endView.getMeasuredWidth() / 2;
		int endY = endtLocation[1];

		Animation mRotateAnimation = new RotateAnimation(0, 180,
				Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
				0.5f);
		mRotateAnimation.setDuration(duration);

		TranslateAnimation translateAnimationX = new TranslateAnimation(0,
				endX, 0, 0);
		translateAnimationX.setInterpolator(new LinearInterpolator());
		translateAnimationX.setRepeatCount(0);// 动画重复执行的次数
		translateAnimationX.setFillAfter(true);
		translateAnimationX.setDuration(duration);

		TranslateAnimation translateAnimationY = new TranslateAnimation(0, 0,
				0, endY);
		translateAnimationY.setInterpolator(new AccelerateInterpolator());
		translateAnimationY.setRepeatCount(0);// 动画重复执行的次数
		translateAnimationY.setFillAfter(true);
		translateAnimationY.setDuration((int) (duration * 1.4));

		AnimationSet mAnimationSet = new AnimationSet(true);

		mAnimationSet.setFillAfter(true);
		mAnimationSet.addAnimation(mRotateAnimation);
		mAnimationSet.addAnimation(mScaleAnimation);
		mAnimationSet.addAnimation(translateAnimationY);
		mAnimationSet.addAnimation(translateAnimationX);
		mAnimationSet.setAnimationListener(animationListener);
		view.startAnimation(mAnimationSet);
		return view;
	}

	/**
	 * @将要执行动画的view 添加到动画层
	 * @param vg
	 *            动画运行的层 这里是frameLayout
	 * @param view
	 *            要运行动画的View
	 * @param location
	 *            动画的起始位置
	 * @return
	 */
	private View addViewToAnimLayout(ViewGroup vg, View view, int[] location) {
		int x = location[0];
		int y = location[1];
		vg.addView(view);
		FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
				SystemTools.dip2px(this, 60), SystemTools.dip2px(this, 60));
		lp.leftMargin = x;
		lp.topMargin = y;
		view.setPadding(5, 5, 5, 5);
		view.setLayoutParams(lp);
		return view;
	}

	/**
	 * @Description: 创建动画层
	 * @param
	 * @return void
	 * @throws
	 */
	private FrameLayout createAnimLayout() {
		ViewGroup rootView = (ViewGroup) this.getWindow().getDecorView();
		FrameLayout animLayout = new FrameLayout(this);
		FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
				FrameLayout.LayoutParams.MATCH_PARENT,
				FrameLayout.LayoutParams.MATCH_PARENT);
		animLayout.setLayoutParams(lp);
		animLayout.setBackgroundResource(android.R.color.transparent);
		rootView.addView(animLayout);
		return animLayout;

	}
}
